/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-30 15:40:52   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zx.cloud.domain.LoanOrder;
import com.zx.cloud.domain.OrderLog;
import com.zx.cloud.domain.OverdueDetail;
import com.zx.cloud.domain.RepayDetail;
import com.zx.cloud.domain.RepayOrder;
import com.zx.cloud.domain.TaskFlag;
import com.zx.cloud.domain.User;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.LoanOrderMapper;
import com.zx.cloud.persistence.OrderLogMapper;
import com.zx.cloud.persistence.OverdueDetailMapper;
import com.zx.cloud.persistence.RepayDetailMapper;
import com.zx.cloud.persistence.RepayOrderMapper;
import com.zx.cloud.persistence.TaskFlagMapper;
import com.zx.cloud.persistence.UserMapper;
import com.zx.cloud.util.DateTimeUtil;
import com.zx.cloud.util.OrderNoUtil;
import com.zx.cloud.util.Page;
import com.zx.cloud.util.SmsCodeUtil;

/**
 * 还款订单表
 */
@SpringBootApplication
@Transactional
@Service
public class TaskService extends CrudServiceImpl<RepayOrder> {

	private static final Logger LOGGER = LoggerFactory.getLogger(TaskService.class);
	@Autowired
	private RepayOrderMapper repayOrderMapper;
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private DictService dictService;
	@Autowired
	private  TaskFlagMapper taskFlagMapper;
	
	@Autowired
	public TaskService(CrudMapper<RepayOrder> mapper) {
		super(mapper);
	}
	/**
	 * @Description:定时发送短信
	 */
	public int taskRepaySendSMS(Long  userId) {
		TaskFlag  taskFlag=new TaskFlag();
		taskFlag.setTaskType(3);//定时发送还款短信
		long count =taskFlagMapper.getTodayCountByType(taskFlag);
		if(count ==0){
			/**定时发送短信*/
			Map<String, Object> params=new HashMap<String, Object>();
			/**当天逾期*/
			params.put("dateType", 0);
			List<RepayOrder>  todayOrders=repayOrderMapper.getTaskRepaySendOrderList(params);
			if (todayOrders.size() > 0) {
				LOGGER.info("======================当天逾期还款订单:"+todayOrders+"==================");
				LOGGER.info("======================当天逾期还款订单数量："+todayOrders.size()+"==================");
				for (int i = 0; i < todayOrders.size(); i++) {
						   sendSMS(todayOrders.get(i), userId);
						}
				}
			/**逾期前一天*/
			params.put("dateType", 1);
			List<RepayOrder>  oneDayOrders=repayOrderMapper.getTaskRepaySendOrderList(params);
			if (oneDayOrders.size() > 0) {
				LOGGER.info("======================逾期前1天还款订单:"+oneDayOrders+"==================");
				LOGGER.info("======================逾期前1天还订单数量："+oneDayOrders.size()+"==================");
				for (int i = 0; i < oneDayOrders.size(); i++) {
						   sendSMS(oneDayOrders.get(i), userId);
						}
				}
			/**逾期前三天*/
			params.put("dateType", 3);
			List<RepayOrder>  threeDayOrders=repayOrderMapper.getTaskRepaySendOrderList(params);
			if (threeDayOrders.size() > 0) {
				LOGGER.info("======================逾期前3天还款订单:"+threeDayOrders+"==================");
				LOGGER.info("======================逾期前3天还订单数量："+threeDayOrders.size()+"==================");
				for (int i = 0; i < threeDayOrders.size(); i++) {
						   sendSMS(threeDayOrders.get(i), userId);
						}
				}
			
			taskFlag.setTaskName("taskRepaySendSMS");
			taskFlag.setCreateTime(OffsetDateTime.now());
			taskFlagMapper.insert(taskFlag);
		}else{
			LOGGER.info("==============定时发送短信===已经执行==============");
		}
		return 1;
	}

    /**
     * @Description:短信
     * @author likun
     * @Create Time: 2017年11月2日上午10:33:00
     */
	public int sendSMS(RepayOrder repayOrder,Long userId) {
		/**还款短信*/
		int returnInt = 0;
		RepayOrder repayOrderData=repayOrderMapper.getRepaySendSMSInfo(repayOrder.getId());
		Map<String, String> params = dictService.getSmsDataConfig(0);
		StringBuilder content=new StringBuilder();
		content=content.append(repayOrderData.getRealName())
				.append("##").append(repayOrderData.getOrderNo())
				.append("##").append(repayOrderData.getRepayAmount())
				.append("##").append(repayOrderData.getExpirationTime().toLocalDateTime());
				
		try {
			params.put("content",   URLEncoder.encode(content.toString(),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		params.put("mobile", repayOrderData.getPhone());
	    params.put("templateId", "2009");  
		//参数：0 表示该短信为接口短信
		returnInt = SmsCodeUtil.sendSmsCode(params);
		/**订单操作日志*/
		orderLogService.insertOrderLog(userId,repayOrder.getId(),2,"定时发送还款短信:"+content);
		return returnInt;
	}
	
	 
}
